/* eslint-disable no-param-reassign */
import { parse } from 'querystring';
import type { EditTreeType } from '@/components/EditTree/data';
import type { ProvinceType } from '@/pages/admin/UserManager/src/data';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg =
  /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// For the official demo site, it is used to turn off features that are not needed in the real development environment
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * 数组对象排序
 */
export const ArrayObjSortByKey = (array: any[], key: string | number) => {
  return array.sort((a, b) => {
    const x = a[key];
    const y = b[key];
    if (x < y) {
      return -1;
    }
    if (x > y) {
      return 1;
    }
    return 0;
  });
};

// 两数组筛选匹配
/**
 *
 * @param aArray 保留的数组
 * @param bArray 用来筛选的数组
 * @param key 根据哪个字段筛选
 * @param isObj bArray是否为数组对象
 * @returns 筛选后的数组
 */
export const filterArray = (
  aArray: any[],
  bArray: any[],
  key: string,
  // isObj: boolean = true,
): any[] => {
  const result: any[] = [];
  bArray.forEach((item: any) => {
    const arrChildren: any = [];
    aArray.forEach((c_item: any) => {
      if (item === c_item[key]) {
        arrChildren.push({
          title: item.title,
          key: item.key,
        });
      }
    });
    const newGradesData = {
      title: item,
      key: item,
      children: arrChildren,
    };
    return result.push(newGradesData);
  });
  return result;
};

// 去出冗余title数据
export const mapData = (mapDatas: EditTreeType[]): any => {
  return mapDatas.map((item: EditTreeType) => {
    return {
      name: item?.name,
      defaultValue: item?.defaultValue,
      path: item?.path,
      key: item?.key,
      disableCheckbox: item?.disableCheckbox,
      authority: item?.authority,
      icon: item?.icon,
      parentKey: item?.parentKey, // 带有该属性则不支持删除
      isEditable: item?.isEditable,
      children: item.children ? mapData(item.children) : null,
    };
  });
};

// 删除权限
export const delAuth = (data: EditTreeType[], authName: string) => {
  data.forEach((item: EditTreeType) => {
    const index = item.authority?.indexOf(authName);
    if ((index as number) > -1) {
      item.authority?.splice(index as number, 1);
    }
    if (item.children) {
      delAuth(item.children, authName);
    }
  });
};

// 得到getBase64
export const getBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

// 省市区数据处理antd格式

export const reduceProvArr = (dataKey: any[], tempArr: ProvinceType[]) => {
  const keyArr = Object.keys(dataKey);
  for (let i = 0; i < keyArr.length; i += 1) {
    const itemObj: ProvinceType = {
      value: keyArr[i],
      label: keyArr[i],
    };
    if (Object.keys(dataKey?.[keyArr?.[i]]) && Object.keys(dataKey?.[keyArr?.[i]])[0] !== '0') {
      itemObj.children = [];
      reduceProvArr(dataKey?.[keyArr?.[i]], itemObj.children);
    } else {
      itemObj.children = [];
      const cDataKey = dataKey?.[keyArr?.[i]];
      for (let j = 0; j < cDataKey.length; j += 1) {
        const cItemObj: ProvinceType = {
          value: cDataKey[j],
          label: cDataKey[j],
        };
        itemObj.children.push(cItemObj);
      }
    }
    tempArr.push(itemObj);
  }
};

// 将base64转换为blob
export const dataURLtoBlob = (dataurl: string) => {
  const arr = dataurl.split(',');
  const mime = arr[0]?.match(/:(.*?);/)?.[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  // eslint-disable-next-line no-plusplus
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};
// 将blob转换为file
export const blobToFile = (theBlob: any, fileName: string) => {
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
};

// base转文件
export const dataURLtoFile = (dataurl: string, filename: string) => {
  // 获取到base64编码
  const arr = dataurl.split(',');
  // 将base64编码转为字符串
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n); // 创建初始化为0的，包含length个元素的无符号整型数组
  // eslint-disable-next-line no-plusplus
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type: 'image/jpeg',
  });
};
